package com.moter.demo01.juc.threadpool;

import java.util.concurrent.*;

public class SevenParameter {
    public static void main(String[] args) {
        //七大参数
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                2,//核心线程数（最小线程数）
                5,//最大线程数
                3,//超时等待时间
                TimeUnit.SECONDS,//超时等待时间单位
                new LinkedBlockingDeque<>(100),//阻塞队列
                Executors.defaultThreadFactory(),//默认的创建线程的工厂
                new ThreadPoolExecutor.AbortPolicy());//默认的策略,满了就抛出异常
        //四大策略



//        new ThreadPoolExecutor.AbortPolicy()
        //超出（最大线程数满了，阻塞队列满了）抛异常
//        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
//            throw new RejectedExecutionException("Task " + r.toString() +
//                    " rejected from " +
//                    e.toString());
//        }
//        Exception in thread "main" java.util.concurrent.RejectedExecutionException:
//        Task com.moter.demo01.juc.threadpool.SevenParameter$$Lambda$1/1096979270@7ba4f24f rejected from
//        java.util.concurrent.ThreadPoolExecutor@3b9a45b3[Running, pool size = 5, active threads = 5, queued tasks = 3, completed tasks = 0]

//        new ThreadPoolExecutor.CallerRunsPolicy()
//        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
//            if (!e.isShutdown()) {
//                r.run();
//            }
//        }
        //超出（最大线程数满了，阻塞队列满了）丢给原来的线程（上一级）
//        main	is running
//        pool-1-thread-1	is running
//        main	is running

//        new ThreadPoolExecutor.DiscardPolicy());
        //超出（最大线程数满了，阻塞队列满了）就把超出的线程丢掉，
//        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
//        }
        //pool-1-thread-1	is running1
        //pool-1-thread-3	is running6
        //pool-1-thread-2	is running2
        //pool-1-thread-2	is running4
        //pool-1-thread-4	is running7
        //pool-1-thread-2	is running5
        //pool-1-thread-5	is running8
        //pool-1-thread-1	is running3
        //pool-1-thread-3	is running59
        //pool-1-thread-4	is running61
        //pool-1-thread-2	is running78

//        new ThreadPoolExecutor.DiscardOldestPolicy())
        ////超出（最大线程数满了，阻塞队列满了）就把超出的线程丢掉，
//        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
//            if (!e.isShutdown()) {
//                e.getQueue().poll();
//                e.execute(r);
//            }
//        }
        for (int i = 1; i < 100; i++) {
            int finalI = i;
            poolExecutor.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "\tis running"+ finalI);
            });
        }
        poolExecutor.shutdown();
    }
}
